package com.alisonyu.spider.Proccessor;

import com.alisonyu.spider.Router.Route;
import com.alisonyu.spider.Router.Router;

import java.util.Iterator;
import java.util.function.Consumer;

public class DefaultProcessor implements Process{
    private Router router;

    //默认的处理器，当所有的路由都不匹配的时候就会调用该处理器
    private Consumer<Context> defaultHandler;

    public DefaultProcessor(Router router){
        this.router = router;
        defaultHandler = context -> {
            String url = context.getRequest().getUrl();
            System.out.println(url+"没有对应的处理器处理");
        };
    }

    @Override
    public void process(Context context) {
        Iterator<Route> iterator = router.RoutesIterator();
        while(iterator.hasNext()){
            Route route = iterator.next();
            if(route.match(context.getRequest().getUrl(),context.getResponse().getContent())){
                route.handle(context);
                return;
            }
        }
        //当所有的路由都不匹配的时候就会调用该处理器
        defaultHandler.accept(context);
    }


}
